import React, { useState } from 'react';
import styles from './index.less';
import top from './top.png';
import { useDispatch, useLocation, useSelector } from 'dva';
import searchIcon from '../../assets/search/searchIcon.png';
import { useIntl, getLocale } from 'umi';
import { Tabs, Toast } from 'antd-mobile';
import { getVenuesList } from '../../servers/service.js';
import InViewPort from '../../components/InViewPort';
import defaultCoverImg from '../../assets/exhibitor/defaultCoverImg.jpg';

export default (props) => {
  const [buttonIndex, setButtonIndex] = useState(0);
  const { venues = [] } = useSelector(({ index }) => index);
  const dispatch = useDispatch();
  const intl = useIntl();
  const [list, setList] = React.useState([]);
  const [searchvalue, setSearchValue] = React.useState('');
  const [pagination, setPagination] = React.useState({ page: 0, size: 10, total: 0 });
  const [tabIndex, setTabIndex] = React.useState(0);

  const currentVenues = [{ number: getLocale() == 'zh-CN' ? '全部' : 'All' }, ...venues];

  React.useEffect(() => {
    dispatch({ type: 'index/getVenues', payload: {}, isReset: true });
  }, []);

  const lang = () => getLocale()?.split('-')[0]?.toUpperCase();

  const getTargetList = ({ id }) => {
    Toast.loading('loading...', 0);
    getVenuesList(
      `web/exhibitorPage?venueId=${id}&language=${lang()}&page=${pagination.page}&size=${
        pagination.size
      }&name=${searchvalue}&isUp=true`, //enabled=true&approved=true&approveResult=APPROVED&&sort=sequence%2CDESC
    )
      .then(({ data }) => {
        setPagination((prevState) => ({ ...prevState, total: data.totalElements }));
        setList((list) => [...list, ...data.content]);
      })
      .finally(() => Toast.hide());
  };

  const getTargetList1 = () => {
    Toast.loading('loading...', 0);
    getVenuesList(
      `web/exhibitorPage?page=${pagination.page}&size=${
        pagination.size
      }&language=${lang()}&name=${searchvalue}&isUp=true`, //enabled=true&approved=true&approveResult=APPROVED&language=${lang()}&
    )
      .then(({ data }) => {
        setPagination((prevState) => ({ ...prevState, total: data.totalElements }));
        setList((list) => [...list, ...data.content]);
      })
      .finally(() => Toast.hide());
  };

  React.useEffect(() => {
    // debugger;
    if (Boolean(venues.length)) {
      if (tabIndex == 0) {
        getTargetList1();
      } else {
        const { id } = venues[tabIndex - 1];
        getTargetList({ id });
      }
    }
  }, [venues, tabIndex, pagination.page]);

  const handleSearch = (list, value) => {
    if (!value) return list;
    return list.filter(
      (item) => (item.name + item.address).toLowerCase().indexOf(value.toLowerCase()) !== -1,
    );
    // return list.filter(() => true);
  };

  const onEnter = () => {
    if (!!list.length && list.length < pagination.total) {
      setPagination((prevState) => ({ ...prevState, page: prevState.page + 1 }));
    }
  };

  const onChange = (i) => {
    setButtonIndex(i);
    setTabIndex(i);
    setList([]);
    setPagination({ page: 0, size: 10 });
  };

  return (
    <div className={styles.page}>
      <div className={styles.searchBox}>
        <input
          placeholder={intl.formatMessage({ id: 'SEARCH_KEYWORDS' })}
          onChange={({ target: { value } }) => setSearchValue(value)}
        />
        <img
          src={searchIcon}
          onClick={() => {
            onChange(0);
            getTargetList1();
          }}
        />
      </div>
      <div className={styles.top}>
        <img src={top} alt="" />
      </div>
      <div className={styles.tabWrapper}>
        {currentVenues.map((item, index) => {
          return (
            <div
              key={index}
              className={`${styles.tabItem} ${buttonIndex == index && styles.selectButtonItem}`}
              onClick={() => {
                onChange(index);
              }}
            >
              <span className={styles.tabTitle}>{item.number}</span>
            </div>
          );
        })}
      </div>
      <div className={styles.bottom}>
        <div className={styles.list}>
          {handleSearch(list, searchvalue)?.map((item, key) => {
            return (
              <div
                key={key}
                className={styles.item}
                onClick={() => props.history.push(`/index/exhibitorDetail/${item.id}`)}
              >
                <div className={styles.img}>
                  <img
                    src={item.properties.coverImage ? item.properties.coverImage : defaultCoverImg}
                    alt=""
                  />
                </div>
                <div className={styles.des}>
                  <div>
                    <img src={item?.properties?.logo} alt="" />
                    <span>{lang() === 'ZH' ? item.name : item.nameEn}</span>
                  </div>
                  {/* <div>{item?.city || item?.province}</div> */}
                </div>
              </div>
            );
          })}
          <InViewPort onEnter={onEnter} />
        </div>
      </div>
    </div>
  );
};
